//
//  RootViewController.swift
//  PageBasedApplicationDemo
//
//  Created by Ravi Shankar on 13/08/14.
//  Copyright (c) 2014 Ravi Shankar. All rights reserved.
//

import UIKit

class RootViewController: UIViewController, UIPageViewControllerDelegate {
  var pageViewController: UIPageViewController?

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    // Configure the page view controller and add it as a child view controller.
    pageViewController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
    pageViewController!.delegate = self

    let startingViewController: DataViewController = modelController.viewControllerAtIndex(index: 0, storyboard: storyboard!)!
    let viewControllers: NSArray = [startingViewController]
    pageViewController!.setViewControllers(viewControllers as? [UIViewController], direction: .forward, animated: false, completion: { _ in })

    pageViewController!.dataSource = modelController

    addChild(pageViewController!)
    view.addSubview(pageViewController!.view)

    // Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
    let pageViewRect = view.bounds
    pageViewController!.view.frame = pageViewRect

    pageViewController!.didMove(toParent: self)

    // Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
    view.gestureRecognizers = pageViewController!.gestureRecognizers
  }

  var modelController: ModelController {
    // Return the model controller object, creating it if necessary.
    // In more complex implementations, the model controller may be passed to the view controller.
    if _modelController == nil {
      _modelController = ModelController()
    }
    return _modelController!
  }

  var _modelController: ModelController?

  // MARK: - UIPageViewController delegate methods

  private func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewController.SpineLocation {
    // Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
    let currentViewController = self.pageViewController!.viewControllers?[0]
    let viewControllers: NSArray = [currentViewController as Any]
    self.pageViewController!.setViewControllers(viewControllers as! [UIViewController], direction: .forward, animated: true, completion: { _ in })

    self.pageViewController!.isDoubleSided = false
    return .min
  }
}
